import ExpertSaveTimes, {
  ExpertAddressprops,
  ExpertTimesProps,
  ExpertUpdateTimes,
} from '@/api/expert';
import { Button, Cell, Checkbox, Divider, Icon, Popup } from '@antmjs/vantui';
import { Text, View } from '@tarojs/components';
import Taro, { useDidShow } from '@tarojs/taro';
import classNames from 'classnames';
import dayjs from 'dayjs';
import { useMemo, useState } from 'react';
import { useRequest } from 'taro-hooks';
import useCustom from './useCustom';

export default function useAdd(props: {
  curDate: string;
  times: ExpertTimesProps[];
  onSuccess: Function;
}) {
  const [show, setShow] = useState<boolean>(false);
  const [checked, setChecked] = useState<number[]>([]);
  const { renderNode: renderCustomNode, open: openCustom } = useCustom({
    date: props.curDate,
    onSuccess: function () {
      refresh();
    },
  });

  //选择过的时段ids
  const seledtedTimes = useMemo(
    () => props.times?.map((i) => i.id),
    [props.times]
  );

  const [selectAddress, setSelectAddress] = useState<ExpertAddressprops>();
  const { data: times, refresh } = useRequest(
    () => ExpertUpdateTimes({ date: props.curDate }),
    {
      ready: show,
      refreshDeps: [props.curDate],
    }
  );

  const { runAsync: runSaveTimeAsync, loading } = useRequest(ExpertSaveTimes, {
    manual: true,
  });

  useDidShow(() => {
    //获取上一页的页面栈
    const pages = Taro.getCurrentPages();
    const curPage = pages[pages.length - 1];
    const selectAddress = curPage.data?.selectAddress as ExpertAddressprops;
    selectAddress && setSelectAddress(selectAddress);
  });

  function renderNode() {
    return (
      <>
        <Popup
          show={show}
          round
          position='bottom'
          style={{
            overflow: 'initial',
            paddingBottom: 'calc(64px + env(safe-area-inset-bottom))',
          }}
        >
          <View className=' absolute right-2 -top-[90px]'>
            <Icon
              className='text-3xl text-white'
              name='close'
              onClick={() => setShow(false)}
            />
          </View>

          <View className='p-4 text-lg font-bold text-black'>新增预约时间</View>
          <Divider className='m-0' />
          <View className='p-4 h-[60vh] overflow-auto'>
            <Text className=' block text-black font-bold text-sm mb-3'>
              当前日期
            </Text>
            <Cell
              title={dayjs(props.curDate).format('YYYY年MM月DD日')}
              border={false}
              className=' shadow-input rounded-lg font-bold'
            />

            <View className=' block text-black font-bold text-sm mb-3 mt-7'>
              请选择时段 <Text className=' text-xs text-gary4'>（可多选）</Text>
            </View>
            <View className='space-y-2'>
              {times?.map((item) => (
                <View
                  key={item.id}
                  onClick={() => {
                    if (item.status === 2) return;

                    const sourceData = [...checked];
                    const index = sourceData.findIndex((i) => i === item.id);
                    if (index !== -1) {
                      sourceData.splice(index, 1);
                    } else {
                      sourceData.push(item.id);
                    }

                    setChecked([...sourceData]);
                  }}
                >
                  <Checkbox
                    className={classNames(
                      'border-2 border-solid pl-4 flex-1 rounded-lg border-gary2',
                      {
                        'border-primary bg-[#EFF3FA] text-primary':
                          checked?.includes(item.id),
                      }
                    )}
                    key={item.id}
                    shape='square'
                    iconSize={25}
                    name={item.id}
                    value={checked?.includes(item.id)}
                    disabled={item.status === 2}
                  >
                    <View className='w-full h-full py-2'>
                      {item.start_time} - {item.end_time}
                    </View>
                  </Checkbox>
                </View>
              ))}
              <Button
                onClick={() => openCustom()}
                block
                className=' border-dashed border-2 border-primary text-primary bg-white'
              >
                自定义时段
              </Button>
            </View>

            <Text className=' block text-black font-bold text-sm mb-3 mt-7'>
              咨询地点
            </Text>
            <Cell
              onClick={() => {
                Taro.navigateTo({
                  url: '/pages/expert/appointment/address',
                });
              }}
              className=' shadow-input rounded-lg'
              border={false}
              title={selectAddress?.address || '请选择'}
              renderRightIcon={
                <View className=' flex items-center'>
                  <View
                    className=' w-4 h-4 bg-cover mr-1'
                    style={{
                      backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-switch.svg)`,
                    }}
                  ></View>
                  <Text className=' text-primary text-xs'>切换</Text>
                </View>
              }
            ></Cell>
          </View>

          <View className='flex space-x-4 px-4 bg-white py-2'>
            <Button
              block
              className=' bg-[#B4B8C4] text-white'
              onClick={() => setShow(false)}
            >
              取消
            </Button>
            <Button
              type='primary'
              block
              loading={loading}
              onClick={async () => {
                if (!checked.length)
                  return Taro.showToast({ title: '请选择时段', icon: 'none' });

                if (!selectAddress)
                  return Taro.showToast({ title: '请选择地址', icon: 'none' });

                await runSaveTimeAsync({
                  date: props.curDate,
                  data: checked.join(','),
                  address: selectAddress?.id,
                });

                setShow(false);
                refresh();
                Taro.showToast({ title: '保存成功' });
                props.onSuccess();
              }}
            >
              保存
            </Button>
          </View>
        </Popup>

        {renderCustomNode()}
      </>
    );
  }

  return {
    renderNode,
    open: () => setShow(true),
  };
}
